package com.zucc.eye.mqtt;

import com.alibaba.fastjson.JSONObject;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * MQTT 推送回调
 */

//@Slf4j
public class PushCallback implements MqttCallback {


    private MqttClient client;
    private MqttConnectOptions options;


    private static final Logger log = LoggerFactory.getLogger(PushCallback.class);


    public PushCallback(MqttClient client, MqttConnectOptions options) {
        this.client = client;
        this.options = options;
    }


    @SneakyThrows
    @Override
    public void connectionLost(Throwable cause) {
//        log.info("断开连接，建议重连" + this);
        log.warn("断开连接，建议重连");
        log.warn("原因: " + cause);
        //断开连接，重连
        int tryTimes = 1;
        while (!client.isConnected()) {
            Thread.sleep(1000);

            log.info("重试第{}次", tryTimes);
//                https://blog.csdn.net/zhan107876/article/details/100935779
            //即使连接上也要先断开再重新连接
//            client.disconnect();  //不这样就重连会报错
//            这里不能断开连接啊，断了就有问题
//            log.info("重新连接");
            client.connect(options);
            log.info("连接完成");
            tryTimes++;

        }
        log.info("重连成功，开始订阅消息");
        //发布相关的订阅
//            订阅
        String[] topic = {"SysInit", "xx", "xx", "xx", "xx"};
        int[] qos = {1, 1, 1, 1, 1};
        client.subscribe(topic, qos);


    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        //log.info(token.isComplete() + "");
    }


    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
//        log.info("Topic: " + topic);
//        log.info("Message: " + new String(message.getPayload()));
        JSONObject jsonObject = JSONObject.parseObject(new String(message.getPayload()));

        PushClient client = PushClient.getInstance();

        if (topic.equals("SysInit")) {

        }


    }

    Double getDoubleFromJSONObject(JSONObject jsonObject, String key) {
        try {
            return jsonObject.getBigDecimal(key).doubleValue();
        } catch (Exception e) {
            try{
                return Double.parseDouble(jsonObject.getString(key));
            }catch (Exception e1){
                return  null;
            }


        }

    }



}